# coding: utf-8

import json
import sys
import re
from typing import List, AnyStr

import pandas as pd

canfuse_pattern = re.compile(
    r'node1\s+([^()\s]+)\(([^()]+)\)\s+and\s+node2\s+([^()\s]+)\(([^()]+)\)\s+can not fuse,'
    r'\s+the reason is \[([^]]+)\]\[([^]]+)\]'
)

output_column_names = ["op_name", "op_type", "module", "reason_type", "key_log", "remark"]


def cannot_fuse(inputs: List[AnyStr], lifting_nodes: List[str], lifting_original_nodes: List[str],
                outputs: List[List[str]]) -> None:
    try:
        with open('./keywords_2_reason_type.json', 'r', encoding='utf-8') as f:
            reason_to_type = json.load(f)
    except FileNotFoundError:
        print("文件未找到")
    except json.JSONDecodeError as err:
        print("JSON 格式错误：", err)

    all_outputs = {}
    for line in inputs:
        result = canfuse_pattern.search(line)
        if result:
            node1_name, node1_type, node2_name, node2_type, reason_code, reason = result.groups()
            no_fuse_reason_type = "unknow"
            if reason in reason_to_type:
                no_fuse_reason_type = reason_to_type[reason]
            # outputs.append([node1_name, node1_type, "canfuse", no_fuse_reason_type, result.group(), "", ""])
            # outputs.append([node2_name, node2_type, "canfuse", no_fuse_reason_type, result.group(), "", ""])
            node_name = node1_name
            if node_name in all_outputs:
                all_outputs[node_name].append(no_fuse_reason_type)
            else:
                all_outputs[node_name] = [no_fuse_reason_type]
            node_name = node2_name
            if node_name in all_outputs:
                all_outputs[node_name].append(no_fuse_reason_type)
            else:
                all_outputs[node_name] = [no_fuse_reason_type]
    for i in range(len(lifting_nodes)):
        lifting_node = lifting_nodes[i]
        lifting_original_node = lifting_original_nodes[i]
        if lifting_node in all_outputs:
            output = [lifting_original_node, "", "canfuse", ";".join(all_outputs[lifting_node]), "", ""]
        else:
            output = [lifting_original_node, "", "canfuse", "周围没有AscBackend节点", "", ""]
        outputs.append(output)


if __name__ == "__main__":
    log_file = sys.argv[0]
    outputs = []
    with open(log_file, 'r', encoding='utf-8') as file:
        inputs = file.readlines()
        lifting_nodes, lifting_original_nodes = [], []
        cannot_fuse(inputs=inputs, lifting_nodes=lifting_nodes, lifting_original_nodes=lifting_original_nodes,
                    outputs=outputs)
    df_output = pd.DataFrame(outputs)
    df_output.columns = output_column_names
    df_output.to_csv("./reasons_for_nofuse.csv", index=False)
